package org.dromara.xxmj.utils;



import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * 雪花算法生成ID
 * @Author 王晨沣 2307105054
 * @Date 2025-05-27 15:15:29
 */
public class SnowFlakeUtil {

    private Long machineId=0L;
    private Long dataCenterId=0L;

    private Snowflake snowflake = IdUtil.getSnowflake(machineId, dataCenterId);

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    public static SnowFlakeUtil getInstance() {
        return IdGenHolder.instance;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(0L, 0L);
    }

    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        this.dataCenterId = dataCenterId;
    }

    public synchronized long id() {
        return snowflake.nextId();
    }

    /**
     * 获取ID
     */
    public static Long getId() {
        return SnowFlakeUtil.getInstance().id();
    }

}
